package com.qf.agro.utils;

import com.qf.agro.pojo.SysLog;
import com.qf.agro.pojo.SysUser;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Date;

/**
 * 切面类
 * 基于AOP的日志记录
 * @author zhy
 */
@Component
@Aspect
public class LogAspect {

	@Autowired
	private HttpServletRequest request;

//	@Autowired
//	private SysLogService sysLogService;

	//环绕通知
	@Around("execution(* com.qf.agro.controller.*.*(..))")
	public Object around(ProceedingJoinPoint point) throws Throwable{ //参数是目标方法
		try {
			Signature signature = point.getSignature();
			MethodSignature methodSignature = (MethodSignature)signature;
			//获取当前执行的方法
			Method targetMethod = methodSignature.getMethod();
			//判断是否具有RequestMapping注解
			if (targetMethod.isAnnotationPresent(RequestMapping.class)) {
				RequestMapping rm = (RequestMapping)targetMethod.getAnnotation(RequestMapping.class);
				SysLog log = new SysLog();
				SysUser user = (SysUser)request.getSession().getAttribute("user");
				log.setUsername(user == null ? "匿名":user.getUsername());
				log.setCreateTime(new Date());
				log.setIp(request.getRemoteAddr());
				log.setCompanyId(user == null ? null:user.getCompanyId());
				log.setCompanyName(user == null ? "": user.getCompanyName());
				log.setAction(rm.name());
				//sysLogService.save(log);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return point.proceed(); //代理方法的返回值
	}
}
